
local PANEL = {}

function PANEL:Init()

	self.pcards = {}
	self.Leader = nil

	self.plistpane = vgui.Create( "DPanelList", self )
	self:AddSheet( "Organization", self.plistpane, "gui/silkicons/group", "All Online Members" )
	
	self:Close()

end

function PANEL:AddSheet( label, panel, icon, tooltip )
	
	panel.Paint = function()
		draw.RoundedBox( 6, 0, 0, self:GetWide(), self:GetTall(), Color( 200, 200, 200, 255 ) )
	end
	DPropertySheet.AddSheet( self, label, panel, icon, false, false, tooltip )
	
end

function PANEL:AddMember( ply )

	for k, v in pairs( self.pcards ) do
		if v:GetPlayer() == ply then
			return
		end
	end
	
	local card = vgui.Create( "OPCard", self.plistpane )
	card:SetPlayer( ply )
	self.plistpane:AddItem( card )
	self:SetSize( ScreenScale( 120 ), ScreenScale( #self.pcards* 26 + 13 ) )
	
	self:InvalidateLayout()
	
	table.insert( self.pcards, card )
	self:Open()
	
end

function PANEL:RemoveMember( ply )
	
	for k, v in pairs( self.pcards ) do
		if v:GetPlayer() == ply then
			if ply == self.Leader then
				self.Leader = nil
			end
			v:Remove()
			v = nil
			table.remove( self.pcards, k )
			break
		end
	end
	self:InvalidateLayout()
	
	if #self.pcards < 1 then
		self:Close()
	end
	
end
	

function PANEL:Paint()
	
	DPropertySheet.Paint( self )

end

function PANEL:PerformLayout()

	DPropertySheet.PerformLayout( self )
	self:SetSize( ScreenScale( 120 ), ScreenScale( #self.pcards* 26 + 13 ) )
	self:SetPos( ScrW()-ScreenScale( 130 ), ScreenScale( 8.5 ) )

end

function PANEL:Open()

	self:SetVisible( true )
	self:SetAlpha( 255 )

end

function PANEL:Close()

	self:SetVisible( false )
	self:SetAlpha( 0 )
	
end

vgui.Register( "OPane", PANEL, "DPropertySheet" )
// End of definition

local function CreateOPane()

	if ( g_Opane ) then
	
		g_Opane:Remove()
		g_Opane = nil
	
	end

	g_Opane = vgui.Create( "OPane" )
	g_Opane:SetVisible( false )

end

// Development command to reload the opane (usually just use gamemode_reload)
concommand.Add( "opane", function(ply) if ply:IsAdmin() then CreateOPane() end end )

// Hook to create the opane at the appropriate time
hook.Add( "OnGamemodeLoaded", "CreateOPane", CreateOPane )

function addMember( um )

	g_Opane:AddMember( um:ReadEntity() )

end
usermessage.Hook( "Joinedorg", addMember )

function removeMember( um )

	g_Opane:RemoveMember( um:ReadEntity() )

end
usermessage.Hook( "Leftorg", removeMember )

function setLeader( um )

	if g_Opane.Leader then
		for k, v in pairs( g_Opane.pcards ) do
			if g_Opane.Leader == v:GetPlayer() then
				v:SetIsLeader( false )
			end
		end
	end
	
	ply = um:ReadEntity()
	
	for k, v in pairs( g_Opane.pcards ) do
		if v:GetPlayer() == ply then
			v:SetIsLeader( true )
			g_Opane.Leader = ply
		end
	end

end
usermessage.Hook( "Neworgleader", setLeader )
